package shopping.event;

import java.util.ResourceBundle;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import shopping.beans.CD;

public class AddEventHandler extends EventHandlerBase {
	private ResourceBundle bundle = ResourceBundle.getBundle("URL");
	
	@Override
	public String getURL_To_Dispatch() {
		return bundle.getString("ADD"); //return "/EShop.jsp";
	}
	
	@Override
	public void process(HttpServletRequest request, HttpServletResponse response) {

		CD aCD = getCD(request);
	
	    for (int i = 0; i < getCDList().size(); i++) {
	        
	    	CD cd = (CD) getCDList().get(i);
	        
	        if (cd.getAlbum().equals(aCD.getAlbum())) {
	            cd.setQuantity(cd.getQuantity() + aCD.getQuantity());
	            getCDList().set(i, cd);
	            return;
	        }
	    }
	
	    getCDList().add(aCD);
	}

	private CD getCD(HttpServletRequest request) { //ham` nay` co the pull up len cho super class
        String myCd = request.getParameter("CD");
        String qty = request.getParameter("qty");
        
        StringTokenizer t = new StringTokenizer(myCd, "|");
        String album = t.nextToken();
        String artist = t.nextToken();
        String country = t.nextToken();
        String price = t.nextToken();
        price = price.replace('$', ' ').trim();
        
        CD cd = new CD();
        cd.setAlbum(album);
        cd.setArtist(artist);
        cd.setCountry(country);
        cd.setPrice(Float.parseFloat(price));
        cd.setQuantity(Integer.parseInt(qty));
        
        return cd;
    }
}
